import { onMounted, onUnmounted } from 'vue';

const scrollHandler = (el, binding) => {
  const { value } = binding;
  const scrollHeight = el.scrollHeight;
  const scrollTop = el.scrollTop;
  const clientHeight = el.clientHeight;

  if (scrollHeight - scrollTop - clientHeight <= 10) {
    value();
  }
};

const infiniteScroll = {
  mounted(el, binding) {
    onMounted(() => {
      el.addEventListener('scroll', () => scrollHandler(el, binding));
    });

    onUnmounted(() => {
      el.removeEventListener('scroll', () => scrollHandler(el, binding));
    });
  },
};

export default infiniteScroll;
